<?php
namespace App\Service\OrderService\OrderInterfaceService;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\PssModel\OrderRefund;
use App\Model\PssModel\OrderRefundLog;
use App\Service\OrderService\OrderRefundService\OrderRefundMessage;
use App\Service\PushService\BusinessPushService;
use App\Model\PssModel\OrderSupplier;
use App\Model\PssModel\OrderRefundGoods;

/**
 * 云仓同步BBC数据物流发货状态
 * 1、退货退款物流信息
 * 2、换货物流信息
 * 3、补寄物流信息
 */
class OrderChannelExpress extends BaseService
{
    /**
     * 退换货物流
     */
    public function index( array $param = [] )
    {
        $binfo  = $param['binfo'];
        $bid    = $binfo['bid'];
        //当前换货申请，仅支持自营BBC业务
        if( $binfo['is_channel'] != 1 ) {
            return Normal::returnCode(Normal::FAIL,"当前换货申请，仅支持自营BBC业务");
        }
        
        $requestData = $param['requestData'];
        if( empty($requestData['order_sn']) ) {
            return Normal::returnCode(Normal::FAIL,"售后订单号order_sn不能为空");
        }

        if( empty($requestData['refund_id']) ) {
            return Normal::returnCode(Normal::FAIL,"售后单refund_id不能为空");
        }

        if( empty($requestData['refund_type']) ) {
            return Normal::returnCode(Normal::FAIL,"售后方式refund_type不能为空");
        }
        
        //当前类型不支持
        $refund_type = $requestData['refund_type'];
        $order_sn    = $requestData['order_sn'];
        $refund_id   = $requestData['refund_id'];
        if( in_array($refund_type,[OrderRefundMessage::refund_type_refundnotgoodsbutmoney]) ) {
            return Normal::returnCode(Normal::FAIL,"售后方式refund_type仅支持换货，退货退款，补寄，其它类型不支持触发当前业务!");
        }
        
        //补寄
        if( $refund_type != OrderRefundMessage::refund_type_refundsendgoods ) {
            if( empty($requestData['change_express_sn']) ) {
                return Normal::returnCode(Normal::FAIL,"消费者发往仓库-换货/补发运单号change_express_sn不能为空");
            }
            
            if( empty($requestData['change_express_name']) ) {
                return Normal::returnCode(Normal::FAIL,"消费者发往仓库-换货/补发运单物流公司change_express_name不能为空");
            }
            
            if( empty($requestData['change_express_time']) ) {
                return Normal::returnCode(Normal::FAIL,"换货/补发运单号（仓库发往消费者）时间change_express_time不能为空");
            }   
            
            if( empty($requestData['warehouse_change_status']) ) {
                return Normal::returnCode(Normal::FAIL,"仓库方确认审核是否通过退换货warehouse_change_status不能为空");
            }
            
            if( !isset(OrderRefund::instance()->warehouse_change_status[$requestData['warehouse_change_status']]) ) {
                return Normal::returnCode(Normal::FAIL,"仓库方确认审核是否通过退换货warehouse_change_status枚举值不正确");
            }
        }
        //如果是换货申请和补寄，则需要校验仓库物流信息
        if( in_array($refund_type,[OrderRefundMessage::refund_type_refundchangegoods,OrderRefundMessage::refund_type_refundsendgoods]) ) {

            if( empty($requestData['warehouse_express_sn']) ) {
                return Normal::returnCode(Normal::FAIL,"换货/退货失败物流寄回单号warehouse_express_sn不能为空");
            }
            
            if( empty($requestData['warehouse_express_name']) ) {
                return Normal::returnCode(Normal::FAIL,"换货/退货失败物流公司warehouse_express_name不能为空");
            }
            
            if( empty($requestData['warehouse_express_time']) ) {
                return Normal::returnCode(Normal::FAIL,"换货/退货失败物流寄回单号（仓库发往消费者）时间warehouse_express_time不能为空");
            }
        }
        
        if( empty($requestData['create_user_id']) ) {
            return Normal::returnCode(Normal::FAIL,"create_user_id不能为空");
        }
        
        if( empty($requestData['create_user_name']) ) {
            return Normal::returnCode(Normal::FAIL,"create_user_name不能为空");
        }
                
        $orderRefund = OrderRefund::instance()->info(['id' =>$refund_id,'bid'=>$bid,'order_sn'=>$order_sn]);
        if( empty($orderRefund)) {
            return Normal::returnCode(Normal::FAIL,"售后申请订单记录不存在，请联系管理员进行核实处理");
        }
        
        $order_refund_id            = $orderRefund['id'];
        $change_express_sn          = $requestData['change_express_sn'];
        $change_express_name        = $requestData['change_express_name'];
        $change_express_time        = $requestData['change_express_time'];
        $warehouse_express_sn       = $requestData['warehouse_express_sn'];
        $warehouse_express_name     = $requestData['warehouse_express_name'];
        $warehouse_express_time     = $requestData['warehouse_express_time'];
        $refund_type_name           = OrderRefund::instance()->refund_type[$refund_type];
        
        //原始订单信息
        $supplierOrder = OrderSupplier::instance()->info(['id'=>$orderRefund['sub_order_id']]);
        if( empty($supplierOrder)) {
            return Normal::returnCode(Normal::FAIL,"原始供应商订单数据不存在，请联系管理员进行核实处理");
        }
        
        //售后对应的商品
        $orderRefundGoods = OrderRefundGoods::instance()->rows(['refund_order_id'=>$order_refund_id]);
        if( empty($orderRefundGoods)) {
            return Normal::returnCode(Normal::FAIL,"售后订单商品数据不存在，请联系管理员进行核实处理");
        }
        $notifyChannelGoods = [];
        foreach ($orderRefundGoods as $item) {
            $notifyChannelGoods[] = [
                'goodsItemId'       => '0',
                'goodsSku'          => (string)$item['skucode'],
                'goodsRefundNum'    => (string)$item['refund_num']
            ];
            unset($item);
        }
        
        
        try
        {
            OrderRefund::instance()->startTrans();
            $updateExpressArr = [
                'warehouse_express_sn'      => $warehouse_express_sn,
                'warehouse_express_name'    => $warehouse_express_name,
                'warehouse_express_time'    => $warehouse_express_time,
                'md'                        => time(),
                'warehouse_change_status'   => $requestData['warehouse_change_status'],
            ];
            
            //和重新发货相关的数据
            if( in_array($orderRefund['refund_type'],[
                OrderRefundMessage::refund_type_goodsandmoney,
                OrderRefundMessage::refund_type_refundchangegoods,
                OrderRefundMessage::refund_type_refundsendgoods]
                ) 
            ) {
                //如果没有仓库发货的情况下,就是退款
                if( $requestData['warehouse_change_status'] == 1 )//审核通过，则，告知下游退款或者仓库发货
                {
                    if ( in_array($orderRefund['refund_type'],[OrderRefundMessage::refund_type_refundchangegoods]) ) {//如果是换货申请
                        $updateExpressArr['refund_status'] = 11;
                    } else if( $orderRefund['refund_type'] == OrderRefundMessage::refund_type_refundsendgoods ) {//如果是补寄
                        $updateExpressArr['refund_status'] = 14;
                    } else {
                        $updateExpressArr['refund_status'] = 6;
                    }
                }
                else
                {
                    //如果审核拒绝了
                    if( $orderRefund['refund_type'] == OrderRefundMessage::refund_type_refundchangegoods )//如果是换货申请拒绝
                    {
                        $updateExpressArr['refund_status'] = 8;
                    } else if( $orderRefund['refund_type'] == OrderRefundMessage::refund_type_goodsandmoney ) {//如果是退货退款被拒收
                        $updateExpressArr['refund_status'] = 10;
                    } else {
                        OrderRefund::instance()->rollback();
                        return Normal::returnCode(Normal::FAIL,"当前状态，需要进行变更步骤操作！");
                    }
                }
            }
            
            //如果不是补寄
            if( $refund_type != OrderRefundMessage::refund_type_refundsendgoods ) {
                //需要判断bbc是否已经回传了 物流单号，发给仓库那边
                if( empty($orderRefund['change_express_sn']) ) {
                    $updateExpressArr = [
                        'change_express_sn'                 => $change_express_sn,
                        'change_express_name'               => $change_express_name,
                        'change_express_time'               => $change_express_time,
                        'warehouse_express_sn'              => $warehouse_express_sn,
                        'warehouse_express_name'            => $warehouse_express_name,
                        'warehouse_express_time'            => $warehouse_express_time,
                        'warehouse_change_status'           => $requestData['warehouse_change_status'],
                        'md'                                => time(),
                    ];
                }
            }
            
            //物流发货状态修改
            $result = OrderRefund::instance()->where('id',$order_refund_id)->where('refund_status','>',1)->update($updateExpressArr);
            if( !$result ) {
                OrderRefund::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,"退换货物流处理失败，请联系管理员进行核实处理");
            }
            
            unset($updateExpressArr['md']);
            //发起下游推送逻辑
            $body = [
                'orderSn'           => (string)$supplierOrder['order_sn'],
                'orderNo'           => (string)$supplierOrder['supplier_csn'],
                'refundType'        => (string)$refund_type,
                'refundTypeName'    => (string)$refund_type_name,
                'goodsList'         => $notifyChannelGoods,
                'expressInfo'       => $updateExpressArr,
                'orderRefundId'     => (string)$order_refund_id
            ];
            $result = BusinessPushService::instance()->pushMessage('OrderChannelExpress',$binfo,$body);
            if( $result['code'] != Normal::SUC ) {
                OrderRefund::instance()->rollback();
                return $result;
            }
            
            //写入订单日志
            OrderRefundLog::instance()->addLog($order_refund_id,"用户发起订单消息-[{$refund_type_name}]", $requestData['create_user_id'], $requestData['create_user_name']);
            OrderRefund::instance()->commit();
            return Normal::returnCode(Normal::SUC,"退换货物流处理完成");
        } 
        catch ( \Throwable $th) 
        {
            OrderRefund::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,"退换货物流处理失败:{$th->getMessage()}，请联系管理员进行核实处理");
        }
    }
}